<template>
  <view class="fboxWrap network-wrap" style="position: relative;background-color: #060e1a; height: calc(100vh);" :data-theme="theme" :class="theme" :style="globalColor.style">
	<HeadCustom :isSpace="false" :isHome="false" :isAppBtn="false"></HeadCustom>
    <!-- <canvas id="canvas" canvas-id="canvas"></canvas> -->
    <view class="wrap" style="width:100%;" :style="{height: height +'px'}">
      <RelationGraph ref="seeksRelationGraph" :styleGraph="styleGraph" :options="graphOptions" :on-node-click="onNodeClick" :on-line-click="onLineClick" />
    </view>
    <view class="c-animation" @click="moreTap"></view>
	<view class="btn-action-group fboxWrap">
		<!-- 附近的人 -->
		<view class="btn-action fboxRow font30 lh44 color-F7F9FF" @click="actionTap('peopleNearby')"><image class="bg-img" src="https://ebc-prod.cdn.benwunet.com/uni-static/img3.3.0/card/network-planet-1.png"></image></view>
		<!-- 可能认识的人 -->
		<view class="btn-action fboxRow font30 lh44 color-F7F9FF" @click="actionTap('acquaintance')"><image class="bg-img" src="https://ebc-prod.cdn.benwunet.com/uni-static/img3.3.0/card/network-planet-2.png"></image></view>
		<!-- 人脉发现 -->
		<view class="btn-action fboxRow font30 lh44 color-F7F9FF" @click="actionTap('NetworkDiscovery')"><image class="bg-img" src="https://ebc-prod.cdn.benwunet.com/uni-static/img3.3.0/card/network-planet-3.png"></image></view>
		<!-- 摇一摇 -->
		<view class="btn-action fboxRow font30 lh44 color-F7F9FF" @click="actionTap('Shake')"><image class="bg-img" src="https://ebc-prod.cdn.benwunet.com/uni-static/img3.3.0/card/network-planet-4.png"></image></view>
	</view>
  </view>
</template>

<script>
import RelationGraph from './relation-graph'
import { getNetwork2 } from '@/api/h5'
import {baseList} from './base'

import GraphData from './graphData'
import Bridge from '@/static/js/bridge.js'
export default {
  components: { RelationGraph },
  data() {
    return {
	theme: getApp().globalData.appTheme,
	globalColor: getApp().globalData.globalColor,
      module: null,
      isDrag: false,
      mouse: null,
      id: '',
      token: '',
      graphOptions: {
        allowShowMiniToolBar: false, // 允许显示迷你工具栏
        allowSwitchLineShape: false, // 允许开关线形状
        allowSwitchJunctionPoint: false, // 允许开关连接点
        moveToCenterWhenResize: true, // 当调整大小时移动到中心
        disableDragNode: true, // 禁用拖拽节点
        defaultJunctionPoint: 'border',
        defaultShowLineLabel: false, // 显示关系文字
        isNeedShowAutoLayoutButton: false, // 显示自动布局按钮
        defaultLineShape: 1, // 5 鱼尾 4 折线 3 生动 2 简洁 1 直线
        layouts: [
          // {
          //   "label": "中心",
          //   "layoutName": "center",
          //   "layoutClassName": "seeks-layout-center",
          //   // "distance_coefficient": 1
          // }
          // {
            
          //   'label': '中心',
          //   'layoutName': 'center',
          //   'layoutClassName': 'seeks-layout-center',
          //   'defaultJunctionPoint': 'border',
          //   'defaultNodeShape': 0,
          //   'defaultLineShape': 1,
          //   'from': 'center',
          //   // 通过这4个属性来调整 tree-层级距离&节点距离
          //   'min_per_width': '200',
          //   'max_per_width': '500',
          //   'min_per_height': '40',
          //   'max_per_height': '60',
          //   'levelDistance': '100' // 如果此选项有值，则优先级高于上面那4个选项
          // }
          {
            label: '自动布局',
            layoutName: 'force',
            layoutClassName: 'seeks-layout-force'
          }
        ],
        disableZoom: true, // 是否禁用图谱的缩放功能
        defaultLineWidth: 0.3,
        useAnimationWhenRefresh: true,
      },
      graphData: null,
      visitorId: '',
      innerHeight: 0,
      w: window.innerWidth,
      innerLeft: 0,
      styleGraph: 'width:100%;height: 100%',
	  href: '',
	  height: 0
    }
  },
  created() {
    Bridge.initHandler((message, responseCallback) => {
      const responseData = '初始化收收到来自Java的数据，回传数据给你'
      responseCallback(responseData)
    })
    this.innerHeight = window.innerWidth
	uni.getSystemInfo({success:(sys)=>{
		this.height = sys.screenHeight - 280
	}})
  },
  onLoad(option) {
	  if(option && option.token){
		this.token = option.token
		this.id = option.id
		this.getList()
	  }
		this.$nextTick(()=>{
			this.getCanvas()
		})
  },
  methods: {
    getLeft(){
      console.log(111)
      alert(window.document.body.scrollLeft)

    },
	getCanvas() {
		//宇宙特效
		let ctx = uni.createCanvasContext('canvas'),
			w = (ctx.width = window.innerWidth),
			h = (ctx.height = window.innerHeight),
			hue = 217,
			stars = [],
			count = 0,
			maxStars = 1100 //星星数量,默认1300
		ctx.width = window.innerWidth
		ctx.height = window.innerHeight

		function random(min, max) {
			if (arguments.length < 2) {
				max = min
				min = 0
			}

			if (min > max) {
				const hold = max
				max = min
				min = hold
			}

			return Math.floor(Math.random() * (max - min + 1)) + min
		}

		function maxOrbit(x, y) {
			const max = Math.max(x, y),
				diameter = Math.round(Math.sqrt(max * max + max * max))
			return diameter / 2
			//星星移动范围，值越大范围越小，
		}

		const Star = function() {
			this.orbitRadius = random(maxOrbit(w, h))
			this.radius = random(60, this.orbitRadius) / 10 //星星大小,值越大星星越小,默认8

			this.orbitX = w / 2
			this.orbitY = h / 2
			this.timePassed = random(0, maxStars)
			this.speed = random(this.orbitRadius) / 80000 //星星移动速度,值越大越慢,默认5W

			this.alpha = random(2, 10) / 10

			count++
			stars[count] = this
		}

		Star.prototype.draw = function() {
			const x = Math.sin(this.timePassed) * this.orbitRadius + this.orbitX,
				y = Math.cos(this.timePassed) * this.orbitRadius + this.orbitY,
				twinkle = random(10)

			if (twinkle === 1 && this.alpha > 0) {
				this.alpha -= 0.05
			} else if (twinkle === 2 && this.alpha < 1) {
				this.alpha += 0.05
			}

			ctx.globalAlpha = this.alpha
			
			const half = 50,
			gradient2 = ctx.createCircularGradient(x - this.radius / 2, y - this.radius / 2, this.radius)
			gradient2.addColorStop(0.025, '#CCC')
			gradient2.addColorStop(0.1, '#214887')
			gradient2.addColorStop(0.25, '#060d19')
			gradient2.addColorStop(1, 'transparent')
			ctx.fillStyle = gradient2
			ctx.beginPath()
			ctx.arc(x - this.radius / 2, y - this.radius / 2, this.radius, 0, Math.PI * 2)
			ctx.fill()
			this.timePassed += this.speed
		}

		for (let i = 0; i < maxStars; i++) {
			new Star()
		}

		function animation() {
			ctx.globalCompositeOperation = 'source-over'
			ctx.globalAlpha = 0.5 //尾巴
			// ctx.setFillStyle('#fff')
			// ctx.fillStyle = '#000'
			ctx.fillStyle = '#060d19'
			// ctx.setFillStyle('hsla(' + hue + ', 64%, 6%, 2)')
			ctx.fillRect(0, 0, w, h)

			ctx.globalCompositeOperation = 'lighter'
			for (let i = 1, l = stars.length; i < l; i++) {
				stars[i].draw()
			}
			ctx.draw()
			// console.log(stars)
			setTimeout(()=>{
			window.requestAnimationFrame(animation)
			},60)
			// animation()
		}
		animation()
	},
    getList() {
      getNetwork2({ id: this.id, token: this.token }).then((res) => {
        this.graphData = new GraphData(res.data)
        this.showSeeksGraph(this.graphData)
      })
    },
    showSeeksGraph(data) {
      const nodes = []
      for (const i in data.users) {
        nodes.push(data.users[i])
      }
      const graphJsonData = {
        rootId: data.rootId,
        nodes: nodes,
        links: data.links
      }
      // 以上数据中的node和link可以参考"Node节点"和"Link关系"中的参数进行配置
      this.$refs.seeksRelationGraph.setJsonData(
        graphJsonData,
        (seeksRGGraph) => {
          console.log(1111111111111111)
          this.setZoom()
          console.log(seeksRGGraph)
          this.getWH(seeksRGGraph)
        }
      )
    },
    getWH(seeksRGGraph){
      const {currentZoomSet:{NMZoomCenter},graphSetting:{canvasOffset:{x,y}}} = seeksRGGraph
      let _min_x = 999999
      let _min_y = 999999
      let _max_x = 0
      let _max_y = 0
      const _padding = 50
      seeksRGGraph.nodeViewList.forEach((thisNode) => {
        if (thisNode.x < _min_x) {
          _min_x = thisNode.x
        }
        if (thisNode.x > _max_x) {
          _max_x = thisNode.x + thisNode.el.offsetWidth
        }
        if (thisNode.y < _min_y) {
          _min_y = thisNode.y
        }
        if (thisNode.y > _max_y) {
          _max_y = thisNode.y + thisNode.el.offsetHeight
        }
      })
      // seeksRGGraph.nodeViewList.forEach((thisNode) => {
      //   thisNode.x = thisNode.x - _min_x + _padding
      //   thisNode.y = thisNode.y - _min_y + _padding
      // })
      console.log(seeksRGGraph.$refs.seeksRelationGraph.getBoundingClientRect())
      const _origin_offset_x = x + _min_x
      const _origin_offset_y = y + _min_y
      console.log('offset:', {
        _origin_offset_x,
        _origin_offset_y,
        _min_x,
        _min_y,
        _max_x,
        _max_y
      })

      const _image_width = _max_x - _min_x + 200 + _padding * 2
      const _image_height = _max_y - _min_y + 100 + _padding * 2
      const pt = _min_y + _padding
      const pl =_min_x // + _padding
      const pr = (_max_x - seeksRGGraph.getWindowWidth())/2 + _padding
      const pb = _max_y- seeksRGGraph.getWindowHeight() + _padding


      // this.styleGraph = `width:${parseInt(_image_width)}rpx;height:${parseInt(_image_height)}rpx;`
      this.styleGraph = `width:100%;height:100%;padding: ${Math.abs(pt/2)}px ${Math.abs(pr)}px ${Math.abs(pb/2)}px ${Math.abs(pl)}rpx;`
      setTimeout(() => {
        const div = document.getElementById('seeksRelationGraph')
        div.scrollTop=Math.abs(pt/2)
        div.scrollLeft=Math.abs(pl/2)
      }, 100);
      console.log( x, y, this.styleGraph)

    },

    onNodeClick(nodeObject, $event) {
      const data = { type: 'info', cardId: nodeObject.id }
      if (!nodeObject.data.isHidden) {
        // eslint-disable-next-line no-prototype-builtins
        if (
          nodeObject.data &&
          nodeObject.data.id &&
          !nodeObject.data.hasOwnProperty('name')
        ) {
          data.type = 'more'
          data.cardId = nodeObject.data.id
        }
        // eslint-disable-next-line no-prototype-builtins
        // if (
        //   this.id != nodeObject.id &&
        //   nodeObject.data.hasOwnProperty('name')
        // ) {
        //   this.id = nodeObject.id
        //   this.getList()
        // }
      } else {
        data.type = 'tips'
        data.cardId = nodeObject.data.id
      }
      console.log(data)
      this.appInteraction(data)
    },
    moreTap(){
      const data = { type: 'more', cardId: this.id }
      this.appInteraction(data)
    },
	actionTap(e){
      const data = { type:e, cardId: this.id }
      this.appInteraction(data)
	},
	appInteraction(data){
      const u = navigator.userAgent;
      if (!/(iPhone|iPad|iPod|iOS)/i.test(u)) {
        try {
          window.android.showUserDataHandler(JSON.stringify(data))
        } catch (err) {
          console.log(err)
        }
      } else {
        Bridge.callHandler('showUserDataHandler', data, () => {
          console.log('showUserDataHandler', '更多')
        })
      }
	},
    onLineClick(lineObject, $event) {
      console.log('onLineClick:', lineObject)
    },
    setZoom() {
      this.$refs.seeksRelationGraph.zoom(-60)
    }
  }
}
</script>

<style>
#canvas {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 0;
  width: 750rpx;
  height: calc(100vh);
}

.c-animation {
  position: fixed;
  right: 20rpx;
  top: 260rpx;
  z-index: 99;
  width: 100rpx;
  height: 100rpx;
  transform:scale(1);
  background: url('./star.png') no-repeat center center/cover;
  animation-timing-function:linear;
  animation: ACTRGScale 2s linear infinite;
}
.wrap{background: red;}
.btn-action-group{
  position: fixed;
  bottom: 60rpx;
  left: 0rpx;
  right: 0rpx;
  z-index: 99;
  padding-left: 18rpx;
  

}
.bg-img{width: 324rpx;height: 176rpx}
.btn-action{ margin:20rpx 0 0 22rpx; background-color: #6959CD;width: 324rpx;height: 176rpx;border-radius: 12rpx;}
.color-F7F9FF{color:#F7F9FF}
@keyframes ACTRGScale {
  0% {
  transform:scale(0.5);
  }

  50% {
  transform:scale(1);
  }
  100% {
  transform:scale(0.5);
  }
}
.graph-wrap{}
.rel-map {
  background: none !important;
  background-position: center center;
  background-size: cover;
}
.network-wrap /deep/ .c-my-node {
  background-position: center center;
  background-size: cover;
  border: 0 none;
  height: 160rpx;
  width: 160rpx;
  border-radius: 50%;overflow: hidden;
}
.rel-node.rel-node-checked {
  transform: translateX(0);
}
.c-node-name {
  margin-top: 40rpx;
  padding: 0 10rpx;
  width: 100%;
  text-align: center;
  text-shadow: 0 0 3px #000;
  /* font-size: 28rpx; */
  word-break: break-all;
}
.c-mb-button:first-child {
  display: none;
}
.c-mb-button:last-child {
  display: none;
}
.c-mb-button[title] {
  display: none;
}
.canvas {
  background: #134985 url('https://ebc-prod.cdn.benwunet.com/uni-static/h5/bg-connection.png') no-repeat center
    center;
  background-size: cover;
}
.b {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
